package com.itheima.web;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itheima.service.OrderService;
import com.itheima.support.Result;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/health")
public class PayNotifyController {

    @DubboReference
    private OrderService orderService;


    /**
     * 支付完成后，异步接受微信支付结果通知的回调地址，获取 notify_url
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/payNotify")
    public String payNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1.接收请求参数（xml）
        ServletInputStream in = request.getInputStream();
        // 2.将xml转为java对象
        XmlMapper xmlMapper = new XmlMapper();
        Map param = xmlMapper.readValue(in, Map.class);

        System.out.println("param ================================ " + param);

        // 3.调用orderService，修改订单状态
//        long orderId = (Long) param.get("out_trade_no");

        String id = (String) param.get("out_trade_no");
        long orderId = Long.parseLong(id);

        orderService.updateState(orderId);

        // 4.返回微信平台，接收成功..
        HashMap<String, String> result = new HashMap<>();
        result.put("return_code", "SUCCESS");
        result.put("return_msg", "OK");
        // 将map转为xml
        String xml = xmlMapper.writeValueAsString(result);
        return xml;
    }
}
